package com.gzucm.Scholarship.task;

import com.gzucm.Scholarship.common.ConstValues;
import com.gzucm.Scholarship.common.enums.SystemKind;
import com.gzucm.Scholarship.common.enums.SystemState;
import com.gzucm.Scholarship.entity.SystemValue;
import com.gzucm.Scholarship.service.RedisService;
import com.gzucm.Scholarship.service.SystemService;
import com.gzucm.Scholarship.util.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

@Slf4j
@Component
@EnableAsync
@EnableScheduling
public class MultiThreadScheduleTask {

    @Autowired
    private SystemService systemService;

    @Autowired
    private RedisService redisService;

    /**
     * 定时设置系统状态
     */
    @Async
    @Scheduled(cron = "1 0 0 * * ?")// 每日00:00:01执行一次
    public void setSystemState() throws Exception {
        LogUtil.log("定时任务 ———— 开启设置系统状态...");
        List<SystemValue> values = systemService.findByKind(SystemKind.SYSTEM_STATE_TIMER);
        if (values.isEmpty()) {
            LogUtil.log("定时任务 ———— 无需设置...");
            return;
        }

        Map<Integer, Date> pMap = new HashMap<>();//优先级MAP
        Date now = new Date();
        SystemState state = null;
        for (SystemValue value : values) {
            state = SystemState.get(value.getCode());
            switch (state) {
                case OPEN_UP:
                    pMap.put(4, value.getDateValue());
                    break;
                case EXAMINE:
                    pMap.put(3, value.getDateValue());
                    break;
                case REPORT:
                    pMap.put(2, value.getDateValue());
                    break;
                case SUSPEND:
                    pMap.put(1, value.getDateValue());
                    break;
                default:
                    LogUtil.error("定时任务 ———— SystemState接收到错误的code...");
                    LogUtil.log("定时任务 ———— 设置系统状态结束...");
                    return;
            }
        }
        Date val;
        for (Integer integer : pMap.keySet()) {
            val = pMap.get(integer);
            if (Objects.isNull(val)) {
                continue;
            }
            if (now.compareTo(val) >= 0) {//当前时间已达到（大于）数据库设置的时间
                state = SystemState.get(integer);//按优先级获取
                Objects.requireNonNull(state, "SystemState 不存在优先级为 " + integer + " 的值");
                redisService.set(ConstValues.REDIS_SYSTEM_STATE, state);
                LogUtil.log("定时任务 ———— 设置系统状态为:{}...", state.getDetail());
                break;
            }
        }
        LogUtil.log("定时任务 ———— 设置系统状态结束...");

    }

}
